<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Resources\Admin\UserResource;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Auth;
use Hash;
use App\Http\Controllers\ApiController;

/**
 * Class AuthController
 * @package App\Http\Controllers\Api\Admin\User
 */
class AuthController extends ApiController
{
    /**
     * AuthController constructor.
     */
    public function __construct()
    {
        $this->middleware('jwt:admin')->only('me');
    }

    /**
     * 登录获取JWT Token
     * @param Request $request
     * @return mixed
     * @throws \Illuminate\Validation\ValidationException
     */
    public function login(Request $request)
    {
        $rules = [
            'email' => [
                'required',
                'exists:users',
            ],
            'password' => 'required',
        ];

        $params = $this->validate($request, $rules);

        $token = auth('admin')->attempt($params);

        if ($token) {
            return $this->success(['token' => $token]);
        } else {
            throw new UnauthorizedHttpException('jwt', 'unauthorized.');
        }
    }


    /**
     * 获取当前登录用户的用户信息
     * @return mixed
     */
    public function me()
    {
        $info = Auth::user();
        $info->load(['role.adminMenus.children']);
        $info->showPermission = true;
        return $this->success(new UserResource($info));
    }
}
